<template>
  <div>
    <div class="editor" style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onChange="handleBlur"
      />
    </div>
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted,watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import axios from "axios";
//文本框模式 默认模式   simple 简洁模式
const mode = "default";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p></p>");

// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     valueHtml.value = "<p></p>";
//   }, 1500);
// });

//工具栏配置
const toolbarConfig = {};
//编辑器配置
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {}};

//图片
editorConfig.MENU_CONF["uploadImage"] = {
  //自定义上传
  async customUpload(file, insertFn) {
    const formData = new FormData();
    formData.append("file", file);
    axios.post("http://localhost:8080/api/upload", formData).then((res) => {
      if (res.status == 200) {
        console.log(res);
        let rs = res.data.data;
        insertFn(rs);
      }
    });
  },
};

//视频
editorConfig.MENU_CONF["uploadVideo"] = {
  // 自定义上传
  async customUpload(file, insertFn) {
    const formData = new FormData();
    formData.append("file", file);
    axios.post("http://localhost:8080/api/upload", formData).then((res) => {
      if (res.status == 200) {
        console.log(res);
        let rs = res.data.data;
        insertFn(rs);
      }
    });
  },
};

//发送请求 显示富文本框中的内容
let getData = (id) => {
  axios.get(`http://localhost:8080/api/wang?id=${id}`).then((res) => {
    if (res.status == 200) {
      valueHtml.value = res.data.data.name;
    }
  });
};

// const props = defineProps({
//   isRead:{
//     type: Boolean,
//     default:false
//   }
// })
// watch(() => props.isRead, (newVal) => {
//   editorConfig.readOnly=newVal
//   console.log("123")
// })

//暴露方法
defineExpose({ getData });


const text = ref("");

//声明事件
const emit = defineEmits(["getText"]);

const handleBlur = (editor) => {
  text.value = editor.getHtml();
  emit("getText", text.value);
};


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

</script>

<style scope>
.editor {
  width: 800px;
}
</style>
